﻿using System;

using NUnit.Core.Extensibility;
using NUnit.Core;

namespace GenReportAddin
{
	[NUnitAddin(Description = "GenReport", Name = "GenReport", Type = ExtensionType.Core)]
	public class GenReport_Listener : EventListener, IAddin
    {
        public void RunFinished(Exception exception)
        {
        }

        public void RunFinished(TestResult result)
        {			
			String fileName = "TestResult_" + DateTime.Now.ToString("ddMMMyyy_HHmm") + ".xml";
			XmlResultWriter xml_writer = new XmlResultWriter(fileName);
			
			xml_writer.SaveTestResult(result);
			Console.WriteLine("GenReport Finished " + result.FullName);
        }

        public void RunStarted(string name, int testCount)
        {
        }

        public void SuiteFinished(TestResult result)
        {
        }

        public void SuiteStarted(TestName testName)
        {
        }

        public void TestFinished(TestResult result)
        {
            //SimpleTestRunner r = new SimpleTestRunner();
            //Console.WriteLine(result.ResultState);
            //Console.WriteLine(result.Test.GetType());

            if (result.ResultState == ResultState.Failure)
            {

                TestMethod tm = result.Test as TestMethod;
                if (tm != null)
                {
                   result = tm.RunTest();
                }
            }
        }

        public void TestOutput(TestOutput testOutput)
        {
        }

        public void TestStarted(TestName testName)
        {
        }

        public void UnhandledException(Exception exception)
        {
        }

        public bool Install(IExtensionHost host)
        {
            IExtensionPoint listeners = host.GetExtensionPoint("EventListeners");
            if (listeners == null)
                return false;

            listeners.Install(this);
            return true;
        }
    }
}
